package com.rsa.advice;

import cn.hutool.json.JSONUtil;
import com.rsa.annotations.RsaSecurityParameter;
import com.rsa.constant.Constant;
import com.rsa.core.R;
import com.rsa.utils.RSAUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 返回数据加密
 */
@ControllerAdvice(basePackages = "com.rsa.controller")
public class RsaDecodeResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    private static final Logger logger = LoggerFactory.getLogger(RsaDecodeResponseBodyAdvice.class);


    /**
     *
     * @param methodParameter
     * @param converterType
     * @return
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class converterType) {
        boolean encode = false;
        if (methodParameter.getMethod().isAnnotationPresent(RsaSecurityParameter.class)) {
            //获取注解配置的包含和去除字段
            RsaSecurityParameter serializedField = methodParameter.getMethodAnnotation(RsaSecurityParameter.class);
            //返回参数是否需要加密
            encode = serializedField.outEncode();
        }
        return encode;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // todo 加密数据 返回给前端
        String strBody = JSONUtil.toJsonStr(body);
        System.out.println("加密数据 返回给前端 : " + strBody);
        logger.info("对方法method :【" + methodParameter.getMethod().getName() + "】接收数据进行解密");
        // new MyHttpInputMessage(body, PUBLIC_KEY)
        String encryptedData = RSAUtils.encryptedDataOnJava(strBody, Constant.PUBLIC_KEY);
//        Map<String, Object> retaMap = new HashMap<>();
//        retaMap.put("code", 200);
//        retaMap.put("msg", "success");
//        retaMap.put("data", encryptedData);
        logger.info("加密后的数据 :【" + encryptedData + "】");
        return R.ok("success", encryptedData);
    }


}
